package com.meringer.beans.ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.meringer.entities.Race;
import com.meringer.entities.RaceResult;
import com.meringer.entities.Road;
import com.meringer.entities.User;

/**
 * Statistics bean
 * @author K.Zlatanov
 */
@Stateless
@LocalBean
public class StatsEJB
{
	@PersistenceContext
	private EntityManager em;
	
    /**
     * Default constructor. 
     */
    public StatsEJB() {
        
    }
    
    /**
     * Return user races stats sorted beginning with the most recent ones.
     */
    public List<RaceResult> getUserRaceResults(User user)
    {
    	TypedQuery<RaceResult> q =
    	em.createQuery("SELECT r FROM RaceResult r WHERE r.user = :user ORDER BY r.id DESC", 
    			            RaceResult.class);
    	q.setParameter("user", user);
    	List<RaceResult> userRaces = q.getResultList();
    	return userRaces;
    }
    
    /**
     * Return user road stats.
     */
    public List<RaceResult> getRoadRaceResults(Road road)
    {
    	TypedQuery<RaceResult> q =
    	em.createQuery("SELECT r FROM RaceResult r, Race c WHERE c.road = :road AND c = r.race", 
    			RaceResult.class);
    	q.setParameter("road", road);
    	List<RaceResult> userRaces = q.getResultList();
    	return userRaces;
    }
    
    /**
     * Return race stats and results for a given race sorted by standings.
     */
    public List<RaceResult> getRaceResults(Long raceID)
    {
    	Race race = em.find(Race.class, raceID);
    	return race==null ? null : race.getSortedRaceResults();
    }

    /**
     * Finds a given race
     */
    public Race getRace(Long raceID)
    {
    	return em.find(Race.class, raceID);
    }

    /**
     * Find out what the user has been awarded on a given race.
     */
    public int getAwardFromRace(User user, Long raceID)
    {
    	if (user==null)
    		return 0;
    	
    	Race race = em.find(Race.class, raceID);
    	if (race != null) {
    		int raceAward = race.getRoad().getAward(); 
    		List<RaceResult> raceResults =  race.getRaceResults();
    		for (RaceResult result : raceResults) {
    			if (result.getUser().getUsername().equals(user.getUsername()))
    			{
    				raceAward = raceAward - (int)(50*((long)result.getPosition()-1));
    				return raceAward < 0 ? 0: raceAward;
    			}
    		}
    	}
    	return 0;
    }
}
